package 力扣._160_相交链表;




public class Solution {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public int getlength(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //得到a、b的长度
        int len_a = getlength(headA);
        int len_b = getlength(headB);
        //较长的先后移长度差
        while (len_a > len_b) {
            headA = headA.next;
            len_a--;
        }
        while (len_b > len_a) {
            headB = headB.next;
            len_b--;
        }
        //a、b双指针同时向后遍历，直到所指向元素相同
        while (headA != null && headB != null) {
            if(headA==headB)
                return headA;
            headA=headA.next;
            headB=headB.next;
        }
        return null;
    }

    public static void main(String[] args) {

    }
}